import { defineStore } from 'pinia'
import { FnOperationControl } from '@utils/object-util/periodic-execution/FnOperationControl'
import { getDeviceAndGatewayStatusAPI } from '@/api/realtime'

/**
 * 获取设备 & 网关在离线地址
 */
async function getDeviceStatus () {
  const res = await getDeviceAndGatewayStatusAPI()
  res.result().then((rdata) => {
    const { deviceList, gateWayList } = rdata.data || { deviceList: [], gateWayList: [] }
    const data = {
      devicesStatus: deviceList.reduce<Record<string, boolean>>((ret, item) => {
        ret[item.id] = item.status
        return ret
      }, {}),
      gatewaysStatus: gateWayList.reduce<Record<string, boolean>>((ret, item) => {
        ret[item.id] = item.status
        return ret
      }, {})
    }
    useDeviceStatusStore().setStatus(data)
  })
}

const statusOperationControl = new FnOperationControl({
  fn: getDeviceStatus,
  pause: true,
  timeout: 5000
})

export const useDeviceStatusStore = defineStore('deviceAndGatewayStatus', {
  state: () => ({
    // 设备状态 - 在离线 Record<设备id, true在线>
    devicesStatus: {} as Record<string, boolean>,
    // 网关状态 - 在离线 Record<设备id, true在线>
    gatewaysStatus: {} as Record<string, boolean>
  }),
  actions: {
    setStatus (value: {
      devicesStatus: Record<string, boolean>
      gatewaysStatus:Record<string, boolean>
    }) {
      this.devicesStatus = value.devicesStatus
      this.gatewaysStatus = value.gatewaysStatus
    },
    startUpdateStatus () {
      statusOperationControl.run()
    },
    stopUpdateStatus () {
      statusOperationControl.stop()
    }
  }
})
